﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Xml.Linq;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.Repository;
using Newtonsoft.Json;
using SqlSugar;
using SqlSugar.Extensions;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;

namespace CoreShop.Services
{
    /// <summary>
    /// 接口实现
    /// </summary>
    public class corecmsfoodordermasterServices : Repository<corecmsfoodordermaster>, IcorecmsfoodordermasterServices
    {
        public bool InsertAsync(corecmsfoodordermaster entity)
        {
            return base.Change<corecmsfoodordermaster>().Insert(entity);
        }
        public bool InsertOrUpdate(List<corecmsfoodordermaster> entity)
        {
            return base.InsertOrUpdate(entity);
        }
        /// <summary>
        /// 重写异步更新方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateAsync(corecmsfoodordermaster entity)
        {
            return base.Change<corecmsfoodordermaster>().Update(a => new corecmsfoodordermaster()
            {
                orderId = entity.orderId,
                orderNo = entity.orderNo,
                number = entity.number,
                orderDate = entity.orderDate,
                storeId = entity.storeId,
                corpId = entity.corpId,
                sumQuantity = entity.sumQuantity,
                sumAmount = entity.sumAmount,
                sumRealAmount = entity.sumRealAmount,
                sumTaskAmount = entity.sumTaskAmount,
                sumFeedAmount = entity.sumFeedAmount,
                sumAllAmount = entity.sumAllAmount,
                sumAllAmount1 = entity.sumAllAmount1,
                sumFloorAmount = entity.sumFloorAmount,
                sumDiscountAmount = entity.sumDiscountAmount,
                sumFreeAmount = entity.sumFreeAmount,
                telephone = entity.telephone,
                ordertype = entity.ordertype,
                deskId = entity.deskId,
                userId = entity.userId,
                payStatus = entity.payStatus,
                status = entity.status,
                sysUserId = entity.sysUserId,
                isUpload = entity.isUpload
            }, a => a.orderId == entity.orderId);
        }

        /// <summary>
        /// 重写异步更新方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateAsync(List<corecmsfoodordermaster> entity)
        {
            bool returnKey = true;
            foreach (var item in entity)
            {
                returnKey = base.Change<corecmsfoodordermaster>().Update(a => new corecmsfoodordermaster()
                {
                    orderId = item.orderId,
                    orderNo = item.orderNo,
                    number = item.number,
                    orderDate = item.orderDate,
                    storeId = item.storeId,
                    corpId = item.corpId,
                    sumQuantity = item.sumQuantity,
                    sumAmount = item.sumAmount,
                    sumRealAmount = item.sumRealAmount,
                    sumTaskAmount = item.sumTaskAmount,
                    sumFeedAmount = item.sumFeedAmount,
                    sumAllAmount = item.sumAllAmount,
                    sumAllAmount1 = item.sumAllAmount1,
                    sumFloorAmount = item.sumFloorAmount,
                    sumDiscountAmount = item.sumDiscountAmount,
                    sumFreeAmount = item.sumFreeAmount,
                    telephone = item.telephone,
                    ordertype = item.ordertype,
                    deskId = item.deskId,
                    userId = item.userId,
                    payStatus = item.payStatus,
                    status = item.status,
                    sysUserId = item.sysUserId,
                    isUpload = item.isUpload

                }, a => a.orderId == item.orderId);
            }
            return returnKey;
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteByIdAsync(long id)
        {
            return base.Change<corecmsfoodordermaster>().DeleteById(id);
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool UpdateUpLoadById(long id)
        {
            return base.Change<corecmsfoodordermaster>().Update(a => new corecmsfoodordermaster()
            {             
                isUpload = true
            }, a => a.orderId == id);
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteByIdsAsync(int[] ids)
        {
            bool returnKey = true;
            foreach (int id in ids)
            {
                returnKey = base.Change<corecmsfoodordermaster>().DeleteById(id);
            }
            return returnKey;
        }
        /// <summary>
        /// 获取未上传的订单
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public List<corecmsfoodordermaster> SelectByCorpId(int corpId, int storeId)
        {
            return base.GetList(a => a.corpId == corpId && a.storeId == storeId && a.isUpload == false).ToList();
        }
        #region 获取缓存的所有数据==========================================================

        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public List<corecmsfoodordermaster> GetCaChe()
        {
            return base.GetList();
        }

        #endregion


        #region 根据条件查询分页数据
        /// <summary>
        /// 根据条件查询分页数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsfoodordermaster> QueryPageAsync(ref int count, int? pageIndex, int? pageSize, string sName)
        {
            List<corecmsfoodordermaster> custos = new List<corecmsfoodordermaster>();
            var where = Expressionable.Create<corecmsfoodordermaster>();
            if (!string.IsNullOrEmpty(sName))
            {
                where = where.And(a => a.number.Contains(sName));
            }
            if (pageIndex >= 1 && pageSize > 0)
            {
                custos = base.AsQueryable().WhereIF(true, where.ToExpression())
                    .ToPageList((int)pageIndex, (int)pageSize, ref count)
                    .OrderBy(a => a.number).ToList();
            }
            else
            {
                custos = base.AsQueryable().WhereIF(true, where.ToExpression()).OrderBy(a => a.number).ToList();
            }
            return custos;
        }
        #endregion

        /// <summary>
        /// 根据条件查询订单
        /// </summary>
        /// <param name="ordertype"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        //public List<corecmsfoodsalemaster> SelectByOrdertype(ref int count, int? pageIndex, int? pageSize, int? ordertype, DateTime? startDate, DateTime? endDate, string str, long sSysUserId = 0,bool IsAbnormal = false)
        public List<corecmsfoodsalemaster> SelectByOrdertype(ref int count, int? pageIndex, int? pageSize, Expressionable<corecmsfoodordermaster, corecmsuser, sysuser, corecmsfoodorderclass> where)
        {
            var list = new corecmsfoodordermasterServices().AsQueryable()
                .LeftJoin<corecmsuser>((a, u) => u.id == a.userId)
                .LeftJoin<sysuser>((a, u, su) => a.sysUserId == su.id)
                .LeftJoin<corecmsfoodorderclass>((a, u, su, c) => a.classId == c.id)
                .Where(where.ToExpression())
                .Select((a, u, su, c) => new corecmsfoodsalemaster
                {
                    orderId = a.orderId,
                    orderNo = a.orderNo,
                    number = a.number,
                    orderDate = a.orderDate,
                    corpId = a.corpId,
                    storeId = a.storeId,
                    sumQuantity = a.sumQuantity,
                    sumAmount = a.sumAmount,
                    sumRealAmount = a.sumRealAmount,
                    sumTaskAmount = a.sumTaskAmount,
                    sumFeedAmount = a.sumFeedAmount,
                    sumReduceAmount = a.sumRealAmount + a.sumTaskAmount + a.sumFeedAmount - a.sumAllAmount,
                    sumDiscountAmount = a.sumDiscountAmount,
                    sumPresentAmount = a.sumPresentAmount,
                    sumAllAmount = a.sumAllAmount,
                    telephone = u.mobile ?? "",
                    ordertype = a.ordertype,
                    userId = (long)a.userId,
                    userName = u.userName ?? "",
                    payStatus = a.payStatus,
                    status = a.status,
                    deskId = a.deskId,
                    deskName = "",
                    sysUserId = a.sysUserId,
                    sysUserName = su.userName,
                    isUpload = (bool)a.isUpload,
                    person = a.person,
                    classNumber = c.classNumber,
                    sourceType = a.sourceType,
                }).With(SqlWith.NoLock).OrderBy(a => a.orderDate, OrderByType.Desc)
                .ToPageList((int)pageIndex, (int)pageSize, ref count)                
                .ToList();//sumReduceAmount = a.sumReduceAmount,
            return list;
        }               
              

        /// <summary>
        /// 获取单据编码
        /// </summary>
        private string GetNumberPos(corecmssystemsetup setup, long classId)
        {
            string str = "";
            string sNumber;
            var numberDetail = new corecmsnumberdetailService();
            var numberModel = numberDetail.SelectDataById((int)GlobalEnumVars.SerialNumberType.零售单号);
            switch (setup.billNumberFirst)
            {
                case (int)GlobalEnumVars.BillNumberFirst.ByClass://每班编号（空值）
                    #region
                    if (CommFunc.ConvertToBigInt(numberModel.classId) != classId)
                    {
                        numberModel.classId = classId;
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = sNumber.PadLeft(setup.billNumberLast, '0');
                    #endregion
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByDate://每日编号（空值）
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = sNumber.PadLeft(setup.billNumberLast, '0');
                    #endregion
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYMMDD://短年月日 (如：220212)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyMMdd") + sNumber.PadLeft(setup.billNumberLast, '0');
                    #endregion                    
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYMM://短年月 (如：2202)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMM").ObjToInt(0) != DateTime.Now.ToString("yyyyMM").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyMM") + sNumber.PadLeft(setup.billNumberLast, '0');
                    #endregion  
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYYYMMDD://长年月日 (如：20220212)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMMdd") + sNumber.PadLeft(setup.billNumberLast, '0');
                    #endregion 
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYYYMM://长年月 (如：202202)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMM").ObjToInt(0) != DateTime.Now.ToString("yyyyMM").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMM") + sNumber.PadLeft(setup.billNumberLast, '0');
                    #endregion 
                    break;
                default:
                    str = DateTime.Now.ToString("yyyyMMddHHssmmfff");
                    break;
            }
            return str;
        }


        /// <summary>
        /// 订单确认下单billtypeId=4
        /// </summary>
        /// <param name="custoType"></param>
        /// <param name="isPrintOrdering">是否打印点菜单</param>
        /// <returns></returns>
        public bool SetOrderDetailPrint(corecmsfoodordermaster orderMaster, List<corecmsfoodorderdetail> orderDetails)
        {
            string strDetail = JsonConvert.SerializeObject(orderDetails);
            var orderings = JsonConvert.DeserializeObject<List<corecmsfoodordering>>(strDetail);

            string orderMasterStr = JsonConvert.SerializeObject(orderMaster);
            var orderingMaster = JsonConvert.DeserializeObject<corecmsfoodorderingmaster>(orderMasterStr);

            bool result = false;
            var foodIds = orderings.Select(p => p.foodId).ToList();
            string sBillTitle = "点 菜 单";
            var foodprintschemes = new corecmsfoodprintschemeServices().AsQueryable().Where(p => foodIds.Contains(p.foodId)).ToList();
            var schemeIdsALl = foodprintschemes.Select(p => p.printSchemeId).ToList();
            HashSet<int> schemeIds = new HashSet<int>(schemeIdsALl);//Ids去重复

            var printschemeList = new corecmsprintschemedetailServices().AsQueryable()
            .Where(p => schemeIds.Contains(p.printSchemeId) && p.selectedFlag == true
            && p.billtypeId == (int)GlobalEnumVars.PrintbillType.Kitchen).ToList();

            var billerInfo = new sysuserServices().GetById(orderMaster.sysUserId);

            //商品沽清处理
            var foodsoldoutServices = new corecmsfoodsoldoutServices();
            var foodSoldouts = foodsoldoutServices.QueryFoodSoldoutByIds(foodIds);

            var deskInfo = new corecmsfooddeskServices().GetById(orderMaster.deskId);
            if (orderMaster.sourceType == (int)GlobalEnumVars.FoodOrderSourceType.Meituan)
            {
                deskInfo.name = EnumHelper.GetDescByValue<GlobalEnumVars.FoodOrderSourceType>(orderMaster.sourceType);
            }

            #region 生成厨房打印数据(按商品)
            var orderingSrv = new corecmsfoodorderingServices();
            long batchId = (long)YitIdHelper.NextId();
            List<corecmsprinttaskdetail> printList = new List<corecmsprinttaskdetail>();
            foreach (var schemeInfo in printschemeList)
            {
                batchId = (long)YitIdHelper.NextId();
                foreach (var item in orderings)
                {
                    item.deskName = deskInfo.name;
                    var foodprints = foodprintschemes.Find(p => p.printSchemeId == schemeInfo.printSchemeId && p.foodId == item.foodId);
                    if (foodprints != null)
                    {
                        var printtask = orderingSrv.GePrintTaskItem(orderingMaster, schemeInfo, item, batchId, billerInfo, deskInfo, (int)GlobalEnumVars.PrintbillType.Kitchen, sBillTitle);
                        printList.Add(printtask);
                    }
                }
            }
            #endregion

            #region 商品沽清处理
            foreach (var item in orderings)
            {
                var foodSoldout = foodSoldouts.Find(p => p.foodId == item.foodId);
                if (foodSoldout != null)
                {
                    foodSoldout.soldout = foodSoldout.soldout - item.quantity;
                    if (foodSoldout.soldout < 0) foodSoldout.soldout = 0;
                }
            }
            #endregion
            result = new corecmsprinttaskdetailServices().InsertOrUpdate(printList);
            if (result)
            {
                if (foodSoldouts != null) foodsoldoutServices.UpdateRange(foodSoldouts);
            }

            return result;
        }

        #region 把订单保存成销售单
        /// <summary>
        /// 订单确认下单billtypeId=4
        /// </summary>
        /// <param name="custoType"></param>
        /// <param name="isPrintOrdering">是否打印点菜单</param>
        /// <returns></returns>
        public bool SaveOrderData(sysuser sysUser, corecmsfoodorderingmaster orderingMaster,
            List<corecmsfoodordering> orderingDetail, List<corecmsfoodorderingtag> orderingTag,
            List<corecmsfoodorderpayment> orderPayment, long classId, corecmsuser member, 
            ref corecmsfoodordermaster orderMaster,ref string resultStr, corecmsuserbalance balance = null)
        {
            var bl = false;
            try
            {
                base.Context.Ado.BeginTran();
                var orderingFeed = new corecmsfoodorderingfeedServices().QueryByOrderId(orderingMaster.orderId);
                var orderingTask = new corecmsfoodorderingtaskServices().QueryByOrderId(orderingMaster.orderId);

                string strMaster = JsonConvert.SerializeObject(orderingMaster);
                string strDetail = JsonConvert.SerializeObject(orderingDetail);
                string strFeed = JsonConvert.SerializeObject(orderingFeed);
                string strTask = JsonConvert.SerializeObject(orderingTask);
                string strTag = JsonConvert.SerializeObject(orderingTag);

                //赠送金额合计
                decimal dPresentSum = orderingDetail.Where(p => p.dataType == (int)GlobalEnumVars.OrderingDataType.Present).Sum(p => p.amount);

                orderMaster = JsonConvert.DeserializeObject<corecmsfoodordermaster>(strMaster);
                orderMaster.isUpload = false;
                orderMaster.classId = classId;
                orderMaster.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                orderMaster.payStatus = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                orderMaster.corpId = sysUser.corpId;
                orderMaster.storeId = sysUser.storeId;
                orderMaster.sysUserId = sysUser.id;
                orderMaster.orderDate = DateTime.Now;
                orderMaster.createTime = DateTime.Now;
                orderMaster.sourceType = (int)GlobalEnumVars.FoodOrderSourceType.Pos;
                orderMaster.sumReduceAmount = orderMaster.sumAmount - dPresentSum + orderMaster.sumFeedAmount + orderMaster.sumTaskAmount - orderMaster.sumAllAmount;
                orderMaster.sumPresentAmount = dPresentSum;

                //if (orderMaster.sumReduceAmount < 0) orderMaster.sumReduceAmount = 0;
                //找零金额
                decimal payAmount = orderPayment.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.cash).Select(p => p.payAmount).Sum();
                decimal takeAmount = orderPayment.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.cash).Select(p => p.takeAmount).Sum();
                if (takeAmount > payAmount) orderMaster.changeAmount = takeAmount - payAmount;

                var orderDetail = JsonConvert.DeserializeObject<List<corecmsfoodorderdetail>>(strDetail);                

                decimal allAmount1;
                decimal reduceAmount;
                //计算抹零和减免返写到明细表
                decimal sumReduceAmount = orderMaster.sumFloorAmount + orderMaster.sumFreeAmount;
                foreach (var item in orderDetail)
                {
                    allAmount1 = item.realAmount + item.taskAmount + item.feedAmount;
                    item.id = CommFunc.GetCorpNextId(sysUser.corpId, YitIdHelper.NextId());
                    item.orderNo = orderMaster.orderNo;
                    item.allAmount1 = allAmount1;
                    item.reduceAmount = 0;
                    item.allAmount = allAmount1;
                    if ((sumReduceAmount != 0) && (allAmount1 != 0) && (orderMaster.sumAllAmount1 != 0))
                    {
                        reduceAmount = Math.Round(sumReduceAmount * (allAmount1 / orderMaster.sumAllAmount1),2);
                        item.reduceAmount = reduceAmount;
                        item.allAmount = allAmount1 - reduceAmount;
                    }
                }
                //处理未分配的金额数
                if (sumReduceAmount != 0)
                {
                    decimal sumReduceAmount1 = orderDetail.Sum(p => p.reduceAmount);
                    if (sumReduceAmount != sumReduceAmount1)
                    {
                        var orderDetailRow = orderDetail.Find(p => p.reduceAmount != 0);
                        if (orderDetailRow != null)
                        {
                            orderDetailRow.reduceAmount = orderDetailRow.reduceAmount + sumReduceAmount - sumReduceAmount1;
                            orderDetailRow.allAmount = orderDetailRow.allAmount1 - orderDetailRow.reduceAmount;
                        }                            
                    }
                }                

                //支付信息
                foreach (var item in orderPayment)
                {
                    item.id = CommFunc.GetCorpNextId(sysUser.corpId, YitIdHelper.NextId());
                }

                //计算会员积分
                orderMaster.userPoint = GetUserintegral(orderMaster, orderDetail, member);

                var orderFeed = JsonConvert.DeserializeObject<List<corecmsfoodorderfeed>>(strFeed);
                var orderTask = JsonConvert.DeserializeObject<List<corecmsfoodordertask>>(strTask);
                var orderTag = JsonConvert.DeserializeObject<List<corecmsfoodordertag>>(strTag);
                bl = new corecmsfoodordermasterServices().InsertOrUpdate(orderMaster);
                if (bl)
                {
                    bl = new corecmsfoodorderdetailServices().InsertOrUpdate(orderDetail);
                    bl = new corecmsfoodorderpaymentServices().InsertOrUpdate(orderPayment);
                    new corecmsfoodorderfeedServices().InsertOrUpdate(orderFeed);
                    new corecmsfoodordertaskServices().InsertOrUpdate(orderTask);
                    new corecmsfoodordertagServices().InsertOrUpdate(orderTag);
                    if (balance != null)
                        new corecmsuserbalanceServices().InsertOrUpdate(balance);
                }
                if (bl)
                {
                    new corecmsfoodorderingmasterServices().DeleteById(orderingMaster.orderId);
                    new corecmsfoodorderingServices().Delete(p => p.orderId == orderingMaster.orderId);
                    new corecmsfoodorderingfeedServices().Delete(p => p.orderId == orderingMaster.orderId);
                    new corecmsfoodorderingtaskServices().Delete(p => p.orderId == orderingMaster.orderId);
                    new corecmsfoodorderingtagServices().Delete(p => p.orderId == orderingMaster.orderId);
                }
                base.Context.Ado.CommitTran();
                new corecmsfooddesktagServices().UpdateDeskTag(orderingMaster.deskId);//更新桌台修改日志
            }
            catch (Exception ex)
            {
                resultStr = ex.Message;
                base.Context.Ado.RollbackTran();
            }

            return bl;
        }

        #endregion

        #region 把订单保存成销售单
        /// <summary>
        /// 订单确认下单billtypeId=4
        /// </summary>
        /// <param name="custoType"></param>
        /// <param name="isPrintOrdering">是否打印点菜单</param>
        /// <returns></returns>
        public bool SetOrderRefund(OrderRefundPost orderRefund ,long classId, corecmsstore store, ref string msg)
        {
            var bl = false;
            try
            {               
                corecmsfoodordermaster orderMaster = orderRefund.orderMaster;
                long sourceId = orderMaster.orderId;
                string sourceNo = orderMaster.orderNo;
                string newOrderNo = "Rt" + sourceNo;
                var ordermasterRt = base.AsQueryable().Where(p => p.sourceId == sourceId).ToList();
                
                //多次退款的单号
                if (ordermasterRt.Count > 0)
                    newOrderNo = "Rt" + sourceNo + string.Format("_{0}", ordermasterRt.Count);
                               
                var orderDetails = orderRefund.orderDetail;
                var orderPayments = orderRefund.orderPayment;
                base.Context.Ado.BeginTran();
                orderMaster.sourceId = sourceId;
                orderMaster.sourceNo = sourceNo;
                orderMaster.orderNo = newOrderNo;
                orderMaster.orderId = CommFunc.GetCorpNextId(store.corpId, YitIdHelper.NextId());
                orderMaster.isUpload = false;
                orderMaster.classId = classId;
                orderMaster.orderDate = DateTime.Now;
                orderMaster.ordertype = (int)GlobalEnumVars.OrderBillType.RefundOrder;
                orderMaster.sumQuantity = -orderMaster.sumQuantity;
                orderMaster.sumAmount = -orderMaster.sumAmount;
                orderMaster.sumRealAmount = -orderMaster.sumRealAmount;
                orderMaster.sumTaskAmount = -orderMaster.sumTaskAmount;
                orderMaster.sumFeedAmount = -orderMaster.sumFeedAmount;
                orderMaster.sumPresentAmount = -orderMaster.sumPresentAmount;
                orderMaster.sumReduceAmount = -orderMaster.sumReduceAmount;
                orderMaster.sumAllAmount = -orderMaster.sumAllAmount;
                orderMaster.sumAllAmount1 = -orderMaster.sumAllAmount1;
                orderMaster.sumFloorAmount = -orderMaster.sumFloorAmount;
                orderMaster.sumDiscountAmount = -orderMaster.sumDiscountAmount;
                orderMaster.sumFreeAmount = -orderMaster.sumFreeAmount;
                orderMaster.userPoint = -orderMaster.userPoint;

                foreach (var orderDetail in orderDetails)
                {
                    orderDetail.sourceId = orderDetail.id;
                    orderDetail.id = YitIdHelper.NextId();
                    orderDetail.orderId = orderMaster.orderId;                    
                    orderDetail.quantity = -orderDetail.quantity;
                    orderDetail.amount = -orderDetail.amount;
                    orderDetail.realAmount = -orderDetail.realAmount;
                    orderDetail.feedAmount = -orderDetail.feedAmount;
                    orderDetail.reduceAmount = -orderDetail.reduceAmount;
                    orderDetail.allAmount1 = -orderDetail.allAmount1;
                    orderDetail.allAmount = -orderDetail.allAmount;
                }
                foreach (var orderPayment in orderPayments)
                {
                    orderPayment.id = YitIdHelper.NextId();
                    orderPayment.orderId = orderMaster.orderId;
                    orderPayment.payAmount = -orderPayment.payAmount;
                    orderPayment.takeAmount = -orderPayment.takeAmount;
                }
                bl = base.InsertOrUpdate(orderMaster);
                if (bl)
                {
                    bl = new corecmsfoodorderdetailServices().InsertOrUpdate(orderDetails);
                    bl = new corecmsfoodorderpaymentServices().InsertOrUpdate(orderPayments);
                }
                base.Context.Ado.CommitTran();
                msg = "退货退款成功。";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                base.Context.Ado.RollbackTran();
            }

            return bl;
        }

        #endregion

        #region 计算会员积分
        /// <summary>
        /// 计算会员积分
        /// </summary>
        /// <returns></returns>
        public int GetUserintegral(corecmsfoodordermaster master, List<corecmsfoodorderdetail> details, corecmsuser member)
        {
            if ((master.userId == 0) || (member == null)) return 0;            
            master.userOldPoint = CommFunc.ConvertToInt32(member.point);
            master.userNewPoint = CommFunc.ConvertToInt32(member.point);
            if (member.VipPointRuleInfo == null) return 0;

            var vipPointRuleInfo = member.VipPointRuleInfo;
            if ((vipPointRuleInfo.enable != 0) || (vipPointRuleInfo.channelType != 0)) return 0;
            if (vipPointRuleInfo.enable != 0) return 0;//积分比例 每消费0元，返回
            int integral = 0;
            decimal orderAmount = master.sumAllAmount;
            var orderDetail = details.Where(p => p.dataType != (int)GlobalEnumVars.OrderingDataType.Refund).ToList();
            var foodIds = details.Select(p => p.foodId).ToList();
            var foodList = new corecmsfoodServices().AsQueryable().Where(p => foodIds.Contains(p.id)).ToList();
            foreach (var item in orderDetail)
            {
                var food = foodList.Find(p => p.id == item.foodId);
                if (food == null) continue;
                if (food.pointType == 1) continue;//商品不积分
                if ((item.realPrice < item.price) && (vipPointRuleInfo.specialItemPoint == 1))
                {
                    orderAmount = orderAmount - item.allAmount;
                    //continue;//特价商品不积分
                }                    
                //orderAmount += item.allAmount;
            }

            if ((orderAmount > 0) && (vipPointRuleInfo.saleAmount > 0))
            {
                integral = (int)(orderAmount / vipPointRuleInfo.saleAmount * vipPointRuleInfo.pointNum);
            }
            master.userNewPoint = CommFunc.ConvertToInt32(member.point)+ integral;
            return integral;            
        }
        #endregion

        /// <summary>
        /// 前台商品销售统计
        /// </summary>
        /// <returns></returns>
        public corecmsfoodordermaster QueryFirst()
        {
            corecmsfoodordermaster orderingmaster = base.Change<corecmsfoodordermaster>()
            .AsQueryable().Where(a => a.orderId > 0)
            .OrderBy(a => a.orderDate, OrderByType.Desc).First();
            return orderingmaster;
        }

    }
}
